package com.googlecode.weathergram;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

public class ImageHelper {

	public static Uri saveImage(Bitmap image, String suffix) {
		File file = getOutputFile(suffix);
		try {
			OutputStream output = new FileOutputStream(file);

			image.compress(CompressFormat.JPEG, 75, output);

			output.flush();
			output.close();
		} catch (Exception e) {
			Log.e(ImageHelper.class.getSimpleName(),
					"Couldn't open OutputStream for cropping");
		}

		return Uri.fromFile(file);
	}

	private static File getOutputFile(String suffix) {
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				"WeatherGram");

		// create storage directory if needed
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("WeatherGram", "failed to create directory");
				return null;
			}
		}

		// create media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		File mediaFile = new File(mediaStorageDir.getPath() + File.separator
				+ "weathergram_" + timeStamp + "_" + suffix + ".jpg");

		return mediaFile;
	}

}
